package com.indigo.rasmus.foobar;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.util.Log;

public class jyDict {

	private static final String TAG = "ericosur";

	public static String Query(String s)  {
		String doc = getDocument( composeQueryURL(s) );
		Log.v(TAG, "get " + doc.length() + " from getDocument()");
		String res = composeResult(doc);
		return res;
	}

	private static String composeQueryURL(String word)  {
		String dictURL = "http://tw.dictionary.yahoo.com/search?p=" + word;
		//System.out.println(dictURL);
		Log.v(TAG, "url: " + dictURL);
		return dictURL;
	}

	/** Show one document, by filename */
	private static String getDocument(String loc) {
		URL webURL = null;
		String total = "";
		try {
			//System.err.println("*** Loading " + loc + "... ***");
			webURL = new URL(loc);
			InputStreamReader isr = new InputStreamReader( webURL.openStream() );
			BufferedReader br = new BufferedReader(isr, 64*1024 );
			String line;
			while ((line = br.readLine()) != null) {
				total += line;
			}
			isr.close();
		} catch (MalformedURLException e) {
			//System.err.println("Load failed: " + e);
			Log.e(TAG, e.toString());
		} catch (IOException e) {
			//System.err.println("IOException: " + e);
			Log.e(TAG, e.toString());
		}
		return total;
	}

	private static String composeResult(String doc)  {

		if (doc.length() == 0)  {
			//System.out.println("null string");
			Log.e(TAG, "jyDict: composeResult() got null arg!");
			return "";
		}

		String rr = "";
		String divp = "<div class=p(\\w+)>(.*?)</div>";
		Pattern p = Pattern.compile(divp, Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(doc);

		while ( m.find() )  {
			String type = m.group(1);
			String line = m.group(2);

		  	line = line.replaceAll("^\\s+", "");
		  	line = line.replaceAll("\\s+$", "");
		  	line = line.replaceAll("<[^>]+>", "");

		  	if (type.equals("cixin")
		  		|| type.equals("chi") || type.equals("eng")
		  		|| type.equals("explain"))
		  	{
		  		rr += line;
		  	}
		}
		return rr;
	}
}
